/*******************************************************************************
 * This file is part of the EEG-database project
 * 
 *   ==========================================
 *  
 *   Copyright (C) 2013 by University of West Bohemia (http://www.zcu.cz/en/)
 *  
 *  ***********************************************************************************************************************
 *  
 *   Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 *   the License. You may obtain a copy of the License at
 *  
 *       http://www.apache.org/licenses/LICENSE-2.0
 *  
 *   Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 *   an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *   specific language governing permissions and limitations under the License.
 *  
 *  ***********************************************************************************************************************
 *  
 *   ScenarioXMLDownloadController.java, 2013/10/02 00:01 Jakub Rinkes
 ******************************************************************************/
package cz.zcu.kiv.eegdatabase.logic.controller.scenario;

import cz.zcu.kiv.eegdatabase.data.dao.AuthorizationManager;
import cz.zcu.kiv.eegdatabase.data.dao.GenericDao;
import cz.zcu.kiv.eegdatabase.data.dao.PersonDao;
import cz.zcu.kiv.eegdatabase.data.pojo.History;
import cz.zcu.kiv.eegdatabase.data.pojo.Person;
import cz.zcu.kiv.eegdatabase.data.pojo.Scenario;
import cz.zcu.kiv.eegdatabase.logic.util.ControllerUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.w3c.dom.Document;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.sql.Blob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;

/**
 * This controller loads a data object for the view which serves the downloading of the data file
 *
 * @author Jindra
 */
public class ScenarioXMLDownloadController extends AbstractController {

    private GenericDao<Scenario, Integer> scenarioDao;
    private GenericDao<History, Integer> historyDao;
    private PersonDao personDao;
    private Log log = LogFactory.getLog(getClass());
    private AuthorizationManager auth;

    public AuthorizationManager getAuth() {
        return auth;
    }

    public void setAuth(AuthorizationManager auth) {
        this.auth = auth;
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //   ModelAndView mav = new ModelAndView("scenarioXMLDownloadView");
        // There should always be set integer value in this field - it is generated by view, not by user
        log.debug("Processing download scenario.");
        int scenarioId = Integer.parseInt(request.getParameter("scenarioId"));
        Scenario scenario = scenarioDao.read(scenarioId);
        //TODO set Blob or XMLType
        //Document xmlType = (Document) scenario.getScenarioType().getScenarioXml();
        //Blob c = (Blob) scenario.getScenarioType().getScenarioXml();

        Person user = personDao.getPerson(ControllerUtils.getLoggedUserName());
        Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
        History history = new History();
        log.debug("Setting downloading scenario");
        history.setScenario(scenario);
        log.debug("Setting user");
        history.setPerson(user);
        log.debug("Setting time of download");
        history.setDateOfDownload(currentTimestamp);
        log.debug("Saving download history");
        historyDao.create(history);
        response.setHeader("Content-Type", scenario.getMimetype());
        response.setHeader("Content-Disposition", "attachment;filename=" + scenario.getScenarioName());
        response.flushBuffer();
        // mav.addObject("dataObject", scenarioDao.read(scenarioId));

        return null;
    }

    private byte[] toByteArray(Object o) throws Exception {
        if(o instanceof Blob) {
            return ((Blob) o).getBytes(1, (int) ((Blob) o).length());
        }
        else if(o instanceof Document) {
            Source source = new DOMSource((Document) o);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            StringWriter stringWriter = new StringWriter();
            Result result = new StreamResult(out);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.transform(source, result);

            return out.toByteArray();
        }

        return null;
    }

    public GenericDao<Scenario, Integer> getScenarioDao() {
        return scenarioDao;
    }

    public void setScenarioDao(GenericDao<Scenario, Integer> scenarioDao) {
        this.scenarioDao = scenarioDao;
    }

    public GenericDao<History, Integer> getHistoryDao() {
        return historyDao;
    }

    public void setHistoryDao(GenericDao<History, Integer> historyDao) {
        this.historyDao = historyDao;
    }

    public PersonDao getPersonDao() {
        return personDao;
    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }


}
